package com.topisv.tms.web.account;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.Role;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.Userrole;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.RoleService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.utils.JobuuidUtils;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 管理员管理用户的Controller.
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/v2/admin/user")
public class UserAdminController extends BaseDataTableController{
	
	private static final Logger log = LoggerFactory.getLogger(UserAdminController.class);
	
	@Autowired
	private AccountService accountService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;

	@RequestMapping(value="page")
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson,"_");
			Page<User> page = accountService.getUsers(paramHolder);
			/*for(User u : page){
				if(StatusEnums.user_type_customer.getStatus().equals(u.getUserType())){
					Customers cust=customersService.findByCustomerCode(u.getCustomerCode());
					if(cust!=null){
						String customerName=cust.getCustomerName();
						u.setCustomerName(customerName);
					}
				}else if(StatusEnums.user_type_paiu.getStatus().equals(u.getUserType())){
					StringBuffer sb=new StringBuffer("");
					String[] lists=u.getCustomers().split(":");
					for(String list:lists){
						Customers cust=customersService.findByCustomerCode(list);
						if(cust!=null){
							if("".equals(sb.toString())){
								sb.append(cust.getCustomerName());
							}else{
								sb.append(":"+cust.getCustomerName());
							}
						}
						
					}
					u.setCustomerName(sb.toString());
				}
			}*/
			// 封装查询结果
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String list(Model model) {
		/*List<User> users = accountService.getAllUser();
		for(User u:users){
			if(StatusEnums.user_type_customer.getStatus().equals(u.getUserType())){
				Customers cust=customersService.findByCustomerCode(u.getCustomerCode());
				if(cust!=null){
					String customerName=cust.getCustomerName();
					u.setCustomerName(customerName);
				}
			}else if(StatusEnums.user_type_paiu.getStatus().equals(u.getUserType())){
				StringBuffer sb=new StringBuffer("");
				String[] lists=u.getCustomers().split(":");
				for(String list:lists){
					Customers cust=customersService.findByCustomerCode(list);
					if(cust!=null){
						if("".equals(sb.toString())){
							sb.append(cust.getCustomerName());
						}else{
							sb.append(":"+cust.getCustomerName());
						}
					}
					
				}
				u.setCustomerName(sb.toString());
			}
			
			
		}
		model.addAttribute("users", users);*/

		return "account/adminUserList";
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		try {
			log.info("开始创建新用户");
			List<Role> roles = roleService.getAllRole();
			List<Customers> customers = customersService.findAll();
			List<AreaGroup> areaGroups=areaGroupService.loadByWarehouseType("paiu");
			List<AreaGroup> customerAreaGroup=areaGroupService.loadByCustomerCode(customers.get(0).getCustomerCode());
			model.addAttribute("customers", customers);
			model.addAttribute("areaGroups", areaGroups);
			model.addAttribute("customerAreaGroup", customerAreaGroup);
			model.addAttribute("roles", roles);
			model.addAttribute("user", new User());
			model.addAttribute("action", "create");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "account/adminUserForm";
	}
	

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid User user, RedirectAttributes redirectAttributes) {
		if(StatusEnums.user_type_customer.getStatus().equals(user.getUserType())){
			user.setJobuuid(JobuuidUtils.createJobuuid(user.getCustomerCode()));
		}else{
			user.setJobuuid(JobuuidUtils.createJobuuid("paiu"));

		}
		log.info("创建新用户："+user.toString());
		
		
//		List<String> customers=user.getCustomerLists();
//		if(customers!=null&&!customers.isEmpty()){
//			StringBuffer sb=new StringBuffer("");
//			for(String customer:customers){
//				if("".equals(sb.toString())){
//					sb.append(customer);
//				}else{
//					sb.append(":"+customer);
//				}
//			}
//			user.setCustomers(sb.toString());
//		}
		user.setCustomers((user.getCustomers()==null?"":user.getCustomers()).replace(",", ":"));
		
//		List<String> areagroups=user.getAreagroupLists();
//		if(!StringUtils.isEmpty(user.getCustomers())){
//		if(customers!=null&&!customers.isEmpty()){
//			StringBuffer sb=new StringBuffer("");
//			for(String areagroup:areagroups){
//				if("".equals(sb.toString())){
//					sb.append(areagroup);
//				}else{
//					sb.append(":"+areagroup);
//				}
//			}
//			user.setAreagroups(sb.toString());
//		}
		user.setAreagroups((user.getAreagroups()==null?"":user.getAreagroups()).replace(",", ":"));
		
		accountService.registerUser(user);
		Long[] roles = user.getRoles();
		if (roles != null && roles.length > 0) {
			for (int i = 0; i < roles.length; i++) {
				Userrole userrole = new Userrole();
				userrole.setUser(user);
				userrole.setRole(roleService.getRole(roles[i]));
				roleService.saveUserrole(userrole);
			}
		}
		redirectAttributes.addFlashAttribute("message", "创建用户成功");
		return "redirect:/v2/admin/user";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		User user=accountService.findOne(id);
		List<AreaGroup> customerAreaGroup=null;
		List<Role> roles = roleService.getAllRole();
		List<Customers> customers = customersService.findAll();
		List<AreaGroup> areaGroups=areaGroupService.findAll();
		if(StatusEnums.user_type_customer.getStatus().equals(user.getUserType())){//商家用户
			 customerAreaGroup=areaGroupService.loadByCustomerCode(user.getCustomerCode());
		}else{
			 customerAreaGroup=areaGroupService.loadByCustomerCode(customers.get(0).getCustomerCode());
		}
		model.addAttribute("customerAreaGroup", customerAreaGroup);
		model.addAttribute("areaGroups", areaGroups);
		model.addAttribute("customers", customers);
		model.addAttribute("roles", roles);
		model.addAttribute("user", user);
		model.addAttribute("action", "update");
		return "account/adminUserForm";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("preloadUser") User user,
			RedirectAttributes redirectAttributes) {
		roleService.deleteUserrole(user.getId());
		Long[] roles = user.getRoles();
		if (roles != null && roles.length > 0) {
			for (int i = 0; i < roles.length; i++) {
				Userrole userrole = new Userrole();
				userrole.setUser(user);
				userrole.setRole(roleService.getRole(roles[i]));
				roleService.saveUserrole(userrole);
			}
		}
		
		String areagroups=user.getAreagroups();
		if(areagroups!=null){
			user.setAreagroups(areagroups.replace(",", ":"));
		}
		if(StatusEnums.user_type_customer.getStatus().equals(user.getUserType())){
			user.setCustomers("");
		}else{
			user.setCustomerCode("");
			String customers=user.getCustomers();
			if(customers!=null){
				user.setCustomers(customers.replace(",", ":"));
			}
		}
		accountService.updateUser(user);
		redirectAttributes.addFlashAttribute("message","更新用户" + user.getUsername() + "成功");
		return "redirect:/v2/admin/user";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id,
			RedirectAttributes redirectAttributes) {
		try {
			User user = accountService.findOne(id);
			accountService.deleteUser(user);
			redirectAttributes.addFlashAttribute("message","删除用户" + user.getUsername() + "成功");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message","删除用户:" + e.getMessage());
		}
		return "redirect:/v2/admin/user";
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出User对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadUser")
	public User getUser(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return accountService.findOne(id);
		}
		return null;
	}
}
